<?php

namespace Frontend;

use BaseController,
    Config,
    Input,
    Lang,
    MyModel,
    Exception,
    Redirect,
    Sentry,
    Str,
    Validator,
    View,
    Category,
    Question,
    GuitarTabs,
    Carbon\Carbon,
    Answer,
    Paginator,
    Request,
    HDServices,
    Response,
    Vote,
    Auth,
    Gregwar\Captcha\CaptchaBuilder,
    Session;

class QuestionsController extends BaseController {

    //put your code here
    public function __construct() {
        return $this->beforeFilter('auth', array('only' => array('getCreate', 'postCreate', 'postCreateAnswer')));
    }

    public function getIndex() {
        Paginator::setPageName('questions_answer');
        $data['questions_vote'] = \Question::orderBy('votes', 'desc')
                ->join('users', 'users.id', '=', 'questions.user_id')
                ->leftjoin('categories', 'categories.id', '=', 'questions.category_id')
                ->select('questions.*', 'users.username', 'categories.title AS category_title')
                ->take(7)
                ->get();
        $data['categories'] = $this->categories();
        return View::make('frontend/questions/index', array('data' => $data));
    }

  

//hỏi đáp mới nhất và hỏi đấp sôi động
    public function postQuestion() {
        if (\Request::ajax()) {
            $param = array_keys(Input::All())[0];
            if (\Input::get($param) != '') {
                $order = $param == 'questions_lastest' ? 'created_at' : 'answers';
                Paginator::setPageName($param);
                $data['questions'] = \Question::join('users', 'users.id', '=', 'questions.user_id')
                        ->leftjoin('categories', 'categories.id', '=', 'questions.category_id')
                        ->orderBy('' . $order, 'desc')
                        ->select('questions.*', 'users.username', 'categories.title AS category_title')
                        ->paginate(15);
                $data['param'] = $param;
                return \Illuminate\Support\Facades\Response::json(View::make('frontend.questions.loadquestion.questions', array('data' => $data))->render());
            }
        }
    }

//ajax câu hỏi tiêu biểu
    public function postHotQuestion() {
        // echo array_keys(Input::All())[0];
        if (!is_null(Input::All())) {
            $data['category_id'] = Input::get('category_id');
            //thể loại câu hỏi
            $data['categories'] = $this->categories();

            Paginator::setPageName('click_next_preview_question');
            $data['hot_question'] = \Question::
                    where('is_hot', '=', 1)
                    ->where(function($where) use ($data) {
                        if ($data['category_id'] > 0)
                            $where->where('category_id', '=', $data['category_id']);
                    })
                    ->paginate(8);
            return \Illuminate\Support\Facades\Response::json(View::make('frontend.questions.hotquestion.hot_question', array('data' => $data))->render());
        }
    }

//load câu trả lời 
    public function postAnswers() {
        if (Input::get('page') != '') {
            $id_question = Input::get('id_question');
            $data['answer_most_like'] = Answer::join('users', 'answers.user_id', '=', 'users.id')
                            ->where('question_id', '=', $id_question)
                            ->where('votes', '<>', 0)
                            ->select('answers.*', 'username')->orderBy('votes', 'DESC')->first();
            ;
            Paginator::setPageName('page');
            $data['answer'] = \Answer::join('users', 'answers.user_id', '=', 'users.id')
                    ->where('question_id', '=', $id_question)
                    ->where(function($where) use ($data) {
                        if (!is_null($data['answer_most_like']))
                            $where->where('answers.id', '!=', $data['answer_most_like']->id);
                    })
                    ->select('answers.*', 'username')
                    ->orderBy('created_at', 'desc')
                    ->paginate(30);
            return \Illuminate\Support\Facades\Response::json(View::make('frontend.questions.loadquestion.question_detail', array('data' => $data))->render());
        }
    }

//add like
    public function postAddlike() {
        if (!is_null($id_answers = Input::get('voteanswer'))) {
            $answer = Answer::find($id_answers);
            if (Sentry::check()) {
                $map = Vote::where('user_id', '=', Sentry::getUser()->id)
                        ->where('answer_id', '=', Request::get('voteanswer'))
                        ->first();
                if (is_null($map)) {
                    $data['test_vote'] = '';
                    $vote = new \Vote;
                    $vote->user_id = Sentry::getUser()->id;
                    $vote->answer_id = Request::get('voteanswer');
                    $vote->save();
                    $answer->votes = $answer->votes + 1;
                    $answer->save();
                } else {
                    $map->delete();
                    $answer->votes = $answer->votes - 1;
                    $answer->save();
                    $data['test_vote'] = 'cheked';
                }
            } else {
                $data['test_vote'] = 'notchek';
            }
            return \Illuminate\Support\Facades\Response::json(View::make('frontend.questions.vote.vote_answer', array('answer' => $answer, 'data' => $data))->render());
        }
    }

//vote question detail
    public function postAddVoteQuestion() {
        if (Input::get('votequestion') == 1) {
            $id_question = Input::get('id_question');
            $data['question'] = Question::find($id_question);
            if (Sentry::check()) {

                $vote = Vote::where('user_id', '=', Sentry::getUser()->id)
                        ->where('question_id', '=', $id_question)
                        ->first();
                if (is_null($vote)) {
                    $data['test_vote'] = '';
                    $vote = new \Vote;
                    $vote->user_id = Sentry::getUser()->id;
                    $vote->question_id = $id_question;
                    $vote->save();
                    $data['question']->votes = $data['question']->votes + 1;
                    $data['question']->save();
                } else {
                    $vote->delete();
                    $data['question']->votes = $data['question']->votes - 1;
                    $data['question']->save();
                    $data['test_vote'] = 'cheked';
                }
            } else {
                $data['test_vote'] = 'notchek';
            }
            return \Illuminate\Support\Facades\Response::json(View::make('frontend.questions.vote.vote_question', array('data' => $data))->render());
        }
    }

    public function getDetail($id, $slug) {

        $data['question'] = Question::join('users', 'users.id', '=', 'questions.user_id')
                ->leftJoin('categories', 'categories.id', '=', 'questions.category_id')
                ->where('questions.id', '=', $id)
                ->select('questions.*', 'username', 'categories.title as category_title')
                ->first();
        $data['question']->views = $data['question']->views + 1;
        $data['question']->save();
        if (is_null($data['question']))
            \App::abort(404);
        $data['answer_most_like'] = Answer::join('users', 'answers.user_id', '=', 'users.id')
                        ->where('question_id', '=', $id)
                        ->where('votes', '<>', 0)
                        ->select('answers.*', 'username')->orderBy('votes', 'DESC')->first();

        Paginator::setPageName('page');
        $data['answer'] = \Answer::join('users', 'answers.user_id', '=', 'users.id')
                ->where('question_id', '=', $id)
                ->where(function($where) use ($data) {
                    if (!is_null($data['answer_most_like']))
                        $where->where('answers.id', '!=', $data['answer_most_like']->id);
                })
                ->select('answers.*', 'username')
                ->orderBy('created_at', 'desc')
                ->paginate(30);
        //thể loại câu hỏi
        $data['categories'] = $this->categories();

        //Các câu hỏi tiêu biểu
        return View::make('frontend/questions/detail', compact('data'));
    }

//tạo câu hỏi 
    function postCreateAnswer($id_question) {
        $data = Input::All();
        $rules = array('content' => 'required');
        $message = array('content.required' => " Bạn chưa nhập nội dung câu trả lời!!!");
        $validation = Validator::make($data, $rules, $message);
        if ($validation->fails()) {
            return Redirect::back()->withInput()->withErrors($validation);
        }
        $answer = new Answer;
        $answer->user_id = Sentry::getUser()->id;
        $answer->question_id = $id_question;
        $answer->content = $data['content'];
        $answer->save();
        $question = Question::find($id_question);
        $question->answers = $question->answers + 1;
        $question->save();
        return Redirect::route('chi-tiet-hoi-dap', array('id' => $id_question, 'name' => Str::slug($question->title)));
    }

//tạo nhanh câu hỏi
    public function postCreateFastQuestion() {
        if (Sentry::check()) {
            $data = Input::All();
            if (Session::get('phrase') != $data['captcha']) {
                return Redirect::back()->with('captcha_error', 'Mã không đúng!!!');
            } else {
                $rules = array('title' => 'required', 'content' => 'required');
                $validation = Validator::make($data['data']['Question'], $rules);
                if ($validation->fails()) {
                    return Redirect::back()->withInput()->withErrors($validation);
                }
                $data['data']['Question']['user_id'] = Sentry::getUser()->id;
                $myModel = new \MyModel();
                $question = $myModel->saveItem('Question', $data['data']['Question'], array('return' => 'class'));

                return Redirect::back()->with('create_fast_question', 'Câu hỏi của bạn đã được lưu');
            }
        } else {
            return Redirect::back()->with('not_login', 'Bạn chưa đăng nhập!!!');
        }
    }

//vote
    public function postVoteAnswer() {
        $answer = Answer::find(Request::get('voteanswer'));
        if (Sentry::check()) {
            $vote = Vote::where('user_id', '=', Sentry::getUser()->id)
                    ->where('answer_id', '=', Request::get('voteanswer'))
                    ->first();
            if (is_null($vote)) {
                $data['test_vote'] = '';
                $vote = new \Vote;
                $vote->user_id = Sentry::getUser()->id;
                $vote->answer_id = Request::get('voteanswer');
                $vote->save();
                $answer->votes = $answer->votes + 1;
                $answer->save();
            } else {
                $vote->delete();
                $answer->votes = $answer->votes - 1;
                $answer->save();
                $data['test_vote'] = 'cheked';
            }
        } else {
            $data['test_vote'] = 'notchek';
        }
    }

    public function categories() {
        $data = \Category::
                where('type', '=', 'lesson')
                ->lists('title', 'id');
        return $data;
    }

}
